// Copyright (c) 2022, hzmes and contributors
// For license information, please see license.txt

frappe.ui.form.on('SRM Supply Plan Of Supplier', {

	setup: function(frm) {
		$(frm.wrapper).on('grid-row-render', function (e, grid_row) {
			if (grid_row.doc.is_default === 0) {
			  grid_row.row.css('background-color', 'yellow')
			}
		});
	},

	onload: function(frm) {
		// 隐藏删除行按钮
		$('*[data-fieldname="orderitem"]').find('.grid-remove-rows').hide();
		// 隐藏子表单[添加行]按钮
		frm.get_field('orderitem').grid.cannot_add_rows = true;
	},

	// onload_post_render: function(frm) {
	// 	// 行记录底色显示 2023-04-23: 渲染完成后调用函数
	// 	// row_color(frm);
	// 	// 点击[下一页]时也能触发
	// 	let nextBtn = document.getElementsByClassName("next-page")[0];
	// 	nextBtn.onclick = function () {row_color(frm);}
	// 	// 点击[最后一页]时也能触发
	// 	let lastBtn = document.getElementsByClassName("last-page")[0];
	// 	lastBtn.onclick = function () {row_color(frm);}
	// 	// 点击[第一页]时也能触发
	// 	let firstBtn = document.getElementsByClassName("first-page")[0];
	// 	firstBtn.onclick = function () {row_color(frm);}
	// },
	
	refresh: function(frm) {
		// 隐藏[删除行]按钮
		$('*[data-fieldname="orderitem"]').find('.grid-remove-rows').hide();
		// 隐藏[全部删除]按钮
		$('*[data-fieldname="orderitem"]').find('.grid-remove-all-rows').hide();
		// 隐藏子表中的"上传"按钮
		$(".grid-upload").hide();
		// 表头字段不允许供应商用户编辑
		let is_allowed = frappe.user_roles.includes('System Manager');
		frm.toggle_enable(['supplier_number', 'supplier_name', 'buyer', 'receive_person', 'is_last'], is_allowed);
		// is_answer=1不允许编辑子表明细
		frm.toggle_enable(['orderitem'], !frm.doc.is_answer);
		// 通过[默认]按钮，以需求日期和数据作为答交, 2023-03-21增加控制: 必须是"最新版本"的才有该按钮
		if (frm.doc.is_last == 1) {
			frm.fields_dict["orderitem"].grid.add_custom_button(__('Default Answer'), 
				function() {
					if (frm.doc.is_answer == 0) {
						//循环子表orderitem
						$.each(frm.doc.orderitem, function(i, d) {
							// console.log(d)
							d.answer_info = d.need_date + "/" + d.assign_qty;
							d.answer_qty = d.assign_qty;
							d.is_default = 1;
						});
						refresh_field("orderitem");
						frm.dirty();
						frm.save();
					}
			});
			frm.fields_dict["orderitem"].grid.grid_buttons.find('.btn-custom').removeClass('btn-default').addClass('btn btn-primary');
		}

		// [采购员]确认[供应商]的答交明细, 即关闭动作: 如果未答交则等同于[默认答交]
		if ( frappe.user.has_role('SRM Purchase') ) {
			frm.add_custom_button(__('采购方确认答交'), function() {
				if (frm.doc.is_answer == 0 ) {
					// 调用py方法
					frappe.call({
						method: "sync_to_erp_answerdetail",
						doc: frm.doc,
						freeze: true,
						freeze_message: __("Creating..."),
						callback: function(r) {
							console.log(r.message);
							frappe.db.set_value(frm.doctype, frm.docname, 'is_answer', 1)
							.then((message) => {
								frm.reload_doc();
								frappe.show_alert("确认并且写入ERP成功!答交确认完成!", 10)
							})
						}
					})
				}
				else {
					frappe.throw("已经确认不允许重复确认!")
				}
			})
		}

		// 2023-09-07: [采购员]确认[供应商]的答交明细后取消确认
		if ( frappe.user.has_role('SRM Purchase') && frm.doc.is_answer === 1) {
			frm.add_custom_button(__('采购方取消确认'), function() {
				frappe.warn('您是要取消供应商的交期回复吗?',
					'这将意味着前一次确认的交期回复(已经写入云星空)也将会取消',
					() => {frappe.db.set_value(frm.doctype, frm.docname, 'is_answer', 0).then((message) => {frm.reload_doc();frappe.msgprint("已取消答交确认!")})
					},
					__('Continue'),
					true // Sets dialog as minimizable
				)
			})
		}

		// 汇总物料代码及交期答交
		frm.add_custom_button(__('Total Confirm'), function() {	
			// 定位当前行
			const current_doc = $('.data-row.editable-row').parent().attr("data-name");
			if (current_doc && cur_frm.doc.is_answer == 0) {
				let data = [];
				// 当前行对象
				const item_row = locals["SRM Supply Plan Of Supplier OrderItem"][current_doc];
				frappe.call({
					method: "query_sum_assignqty",
					doc: cur_frm.doc,
					args:{ material_number: item_row.material_number },
					freeze: true,
					freeze_message: __("Creating..."),
					callback: function(r) {
						if (r.message) {
							data = r.message;
							console.log(data);
						}
					}
				}).then(()=>{
					console.log(item_row)
					// 定义弹窗的子表字段(有参考价值)
					const fields = [{
						fieldtype:'Read Only',
						fieldname:"need_date",
						in_list_view: 1,
						read_only: 1,
						disabled: 1,
						label: __('Date'),
					}, {
						fieldtype:'Read Only',
						fieldname:"assign_qty",
						default: 0,
						read_only: 1,
						disabled: 1,
						in_list_view: 1,
						label: __('Qty')
					}, {
						fieldtype:'Check',
						fieldname:"yes_or_no",
						default: 0,
						read_only: 0,
						in_list_view: 1,
						label: __('Yes')
					}];
					
					// 定义Dialog
					let dialog = new frappe.ui.Dialog({
						title: __("Total Confirm"),
						// 大窗口
						size: 'large',
						// 定义弹窗的所有字段
						fields: [
							{
								fieldtype:'Data',
								fieldname:"material_number",
								default: item_row.material_number,
								read_only: 1,
								hidden: 0,
								label: __('Material Number')
							},
							{
								fieldtype: "Column Break"
							},
							{
								fieldtype:'Data',
								fieldname:"material_name",
								default: item_row.material_name,
								read_only: 1,
								hidden: 0,
								label: __('Material Name')
							},
							{
								fieldtype: "Column Break"
							},
							{
								fieldtype:'Data',
								fieldname:"material_model",
								default: item_row.material_model,
								read_only: 1,
								hidden: 0,
								label: __('Material Model')
							},
							{
								fieldtype: "Section Break"
							},
							// 定义弹窗中的表字段(很有参考价值)
							{
								fieldname: "answer_items",
								// 通过fieldtype定义
								fieldtype: "Table",
								label: "Items",
								cannot_add_rows: 1,
								
								in_place_edit: true,
								reqd: 1,
								data: data,
								// get_data: () => {
								// 	return data;
								// },
								fields: fields
							},
						],
						primary_action: function(values) {
							let yes_items = [];
							values.answer_items.forEach(i => {
								if (i.yes_or_no == 1) {
									yes_items.push({"material_number": values.material_number, "need_date": i.need_date})
								}
							})
							yes_items.forEach(item => {
								console.log(item)
								//循环子表orderitem
								$.each(cur_frm.doc.orderitem, function(i, d) {
									if (d.material_number == item.material_number && d.need_date == item.need_date) {
										console.log(d);
										d.answer_info = d.need_date + "/" + d.assign_qty;
										d.answer_qty = d.assign_qty;
										d.is_default = 1;
									}
								});
							})
							cur_frm.refresh_field("orderitem");
							cur_frm.dirty();
							cur_frm.save();

							dialog.hide();
						},
						primary_action_label: __('Confirm')
					});

					dialog.show();
				})
			}
			else {
				frappe.msgprint("请定位行并且采购方未确认答交")
			}
		})
		
		// 送货单事后修复交期回复表中的relation_qty和delivery_qty
		if ( frappe.user.has_role('Administrator') ) {
			frm.add_custom_button(__('修正送货关联数量'), function() {	
				frappe.call({
					method: "sync_relation_qty",
					doc: cur_frm.doc,
					freeze: true,
					freeze_message: __("Creating..."),
					callback: function(r) {frappe.show_alert("已修复", 10);}
				})
			})
		}

		// 临时指定MPQ
		if ( frappe.user.has_role('SRM Purchase') ) {
			frm.add_custom_button(__('临时MPQ'), function() {	
				let d = new frappe.ui.Dialog({
					title: '临时指定MPQ',
					fields: [
						{
							label: __('Material Number'),
							fieldname: 'material_number',
							fieldtype: 'Data',
							reqd: 1
						},
						{
							label: __('MPQ'),
							fieldname: 'mpq',
							fieldtype: 'Float',
							reqd: 1
						}
					],
					primary_action_label: 'Submit',
					primary_action(values) {
						console.log(values);
						let index = frm.doc.orderitem.findIndex(item => {return item.material_number == values.material_number});
						if (index >= 0) {
							frappe.call({
								method: "update_mpq",
								doc: frm.doc,
								args: {material_number: values.material_number, mpq: values.mpq},
								freeze: true,
								freeze_message: __("Creating..."),
								callback: function(r) {frappe.show_alert("已修改成功!", 10);}
							})
						}
						else {frappe.msgprint("录入物料编码不存在当前表体行!")}
						d.hide();
					}
				});
				
				d.show();
			})
		}
	},

	before_save(frm) {
		// if (frm.doc.is_answer == 1) {
		// 	frappe.throw("答交关闭修改无效")
		// }
		// 行记录的答交数量不允许<=0
		if (frm.doc.orderitem) {
			frm.doc.orderitem.forEach(row => {
				if (row.answer_qty < row.assign_qty || row.answer_date > row.need_date) {
					row.is_default = 0;
				}
				if (row.answer_qty == row.assign_qty && row.answer_date == row.need_date) {
					row.is_default = 1;
				}
				// 2023-04-23: 作废以下代码
				// if (row.answer_info == row.need_date + "/" + row.assign_qty) {
				// 	row.is_default = 1;
				// }
				// if (row.answer_info != row.need_date + "/" + row.assign_qty) {
				// 	row.is_default = 0;
				// }
			})
		}
	},
	
});

frappe.ui.form.on('SRM Supply Plan Of Supplier OrderItem', {
	// refresh: function(frm, cdt, cdn) {
		
	// },
	// 以下是子表编辑窗口的隐藏控制
	form_render(frm, cdt, cdn){
        frm.fields_dict.orderitem.grid.wrapper.find('.grid-delete-row').hide();
        // frm.fields_dict.items.grid.wrapper.find('.grid-duplicate-row').hide();
        // frm.fields_dict.items.grid.wrapper.find('.grid-move-row').hide();
        frm.fields_dict.orderitem.grid.wrapper.find('.grid-append-row').hide();
        frm.fields_dict.orderitem.grid.wrapper.find('.grid-insert-row-below').hide();
        frm.fields_dict.orderitem.grid.wrapper.find('.grid-insert-row').hide();
		
    },
	// answer按钮调用answer方法
	answer: function(frm, cdt, cdn){
		if (frm.doc.is_last == 1) {
			let d = locals[cdt][cdn]
			// 传参
			answer_data({
				frm: frm,
				cdt: cdt,
				cdn: cdn,
				row_name: d.name,
				assign_qty: d.assign_qty,
				need_date: d.need_date,
				answer_info: d.answer_info,
				material_model: d.material_model,
			})
		}
		else if (frm.doc.is_last == 0) { frappe.msgprint("只对最新版本进行交期回复!非最新版本只用来查询检索!")}
	},

});

// 答交方法
let answer_data = function(opts) {
	let frm = opts.frm;
	// 定义data变量
	let data = [];
	// 如果已经有答交明细则赋值data
	if (opts.answer_info) {
		// 获取已有的answer_info
		let answer_info_get = opts.answer_info;
		// 字符串split
		let d = answer_info_get.split(",");
		// forEach循环
		d.forEach((item) => {
			// 把answer_date和qty赋值到对象obj
			const obj = {"answer_date": item.split("/")[0], "qty": item.split("/")[1]}; 
			// 把obj push到data
			data.push(obj);
		});
	}
	// 如果没有答交明细(第一次答交),则data默认为assign_qty和need_date
	else {data = [{"answer_date": opts.need_date, "qty": opts.assign_qty}]}
	// 定义弹窗的子表字段(有参考价值)
	const fields = [{
		fieldtype:'Date',
		fieldname:"answer_date",
		in_list_view: 1,
		read_only: 0,
		disabled: 0,
		label: __('Date'),
	}, {
		fieldtype:'Float',
		fieldname:"qty",
		default: 0,
		read_only: 0,
		in_list_view: 1,
		label: __('Qty')
	}];
	// 定义Dialog
	const dialog = new frappe.ui.Dialog({
		title: __("Answer Submit"),
		// 定义弹窗的所有字段
		fields: [
			{
				fieldtype:'Data',
				fieldname:"row_name",
				default: opts.row_name,
				read_only: 1,
				hidden: 1,
				label: __('Qty')
			},
			{
				fieldtype:'Data',
				fieldname:"material_model",
				default: opts.material_model,
				read_only: 1,
				hidden: 0,
				label: __('Material Model')
			},
			{
				fieldtype: "Column Break"
			},
			{
				fieldtype:'Data',
				fieldname:"assign_qty",
				default: opts.assign_qty,
				read_only: 1,
				label: __('Assign Qty')
			},
			{
				fieldtype: "Column Break"
			},
			{
				fieldtype:'Date',
				fieldname:"need_date",
				default: opts.need_date,
				read_only: 1,
				label: __('Need Date')
			},
			{
				fieldtype: "Section Break"
			},
			// 定义弹窗中的表字段(很有参考价值)
			{
				fieldname: "answer_items",
				// 通过fieldtype定义
				fieldtype: "Table",
				label: "Items",
				cannot_add_rows: 0,
				in_place_edit: true,
				reqd: 1,
				data: data,
				get_data: () => {
					return data;
				},
				fields: fields
			},
		],
		primary_action: function() {
			// 变量定义
			let answer_info_confirm = [];
			let sum_answer_qty = 0;
			// 初始化late_date为[需求日期]
			let late_date;
			// 获取窗口中的子表明细
			const answer_items = this.get_values()["answer_items"].filter((item) => !!item.answer_date);
			answer_items.forEach((item) => {
				// 把子表行拼接: answer_date + "/" + item.qty
				// 并且push到answer_info_confirm
				if(item.answer_date < frappe.datetime.get_today()) {
					frappe.throw('日期不能小于今天')
				}
				else{
					answer_info_confirm.push(item.answer_date + "/" + item.qty );
					// 把子表的qty求sum,注意要flt函数
					// console.log(item.qty);
					sum_answer_qty += flt(item.qty);
					// 如果当前答交日期大于初始化的late_date则赋值
					if (item.answer_date > opts.need_date) { late_date = item.answer_date };
				}
			})
			
			// 赋值
			if (sum_answer_qty <= opts.assign_qty) 
			{
				// 弃用
				// frappe.db.set_value('SRM Supply Plan Of Supplier OrderItem', opts.row_name, {'answer_info': answer_info_confirm.toString(), 'answer_qty': sum_answer_qty})
				// .then(r => {frm.reload_doc()})
				// 获取行记录
				let row_name = locals[opts.cdt][opts.row_name];
				// console.log(sum_answer_qty);
				row_name.answer_info = answer_info_confirm.toString();
				row_name.answer_qty = sum_answer_qty;
				// 2023-04-23: 利用已有未启用的字段answer_date, 等同于最迟答交日期
				if (late_date) {row_name.answer_date = late_date;}
				else{row_name.answer_date = row_name.need_date;}
				row_name.comfirm = 1;
				frm.dirty();
				frm.save();
			}
			else{
				frappe.throw('超出需求总数量');
			}
			this.hide();
		},
		primary_action_label: __('Confirm')
	});

	dialog.show();
}

frappe.ui.keys.add_shortcut({
    shortcut: 'ctrl+q',
    action: () => {
		// let data = [{"need_date": "2023-03-30", "assign_qty": 12345, "yes_or_no": 0}]
		// 定位当前行
		const current_doc = $('.data-row.editable-row').parent().attr("data-name");
		if (current_doc && cur_frm.doc.is_answer == 0) {
			let data = [];
			// 当前行对象
			const item_row = locals["SRM Supply Plan Of Supplier OrderItem"][current_doc];
			frappe.call({
				method: "query_sum_assignqty",
				doc: cur_frm.doc,
				args:{ material_number: item_row.material_number },
				freeze: true,
				freeze_message: __("Creating..."),
				callback: function(r) {
					if (r.message) {
						data = r.message;
						console.log(data);
					}
				}
			}).then(()=>{
				console.log(item_row)
				// 定义弹窗的子表字段(有参考价值)
				const fields = [{
					fieldtype:'Read Only',
					fieldname:"need_date",
					in_list_view: 1,
					read_only: 1,
					disabled: 1,
					label: __('Date'),
				}, {
					fieldtype:'Read Only',
					fieldname:"assign_qty",
					default: 0,
					read_only: 1,
					disabled: 1,
					in_list_view: 1,
					label: __('Qty')
				}, {
					fieldtype:'Check',
					fieldname:"yes_or_no",
					default: 0,
					read_only: 0,
					in_list_view: 1,
					label: __('Yes')
				}];
				
				// 定义Dialog
				let dialog = new frappe.ui.Dialog({
					title: __("Total Confirm"),
					// 大窗口
					size: 'large',
					// 定义弹窗的所有字段
					fields: [
						{
							fieldtype:'Data',
							fieldname:"material_number",
							default: item_row.material_number,
							read_only: 1,
							hidden: 0,
							label: __('Material Number')
						},
						{
							fieldtype: "Column Break"
						},
						{
							fieldtype:'Data',
							fieldname:"material_name",
							default: item_row.material_name,
							read_only: 1,
							hidden: 0,
							label: __('Material Name')
						},
						{
							fieldtype: "Column Break"
						},
						{
							fieldtype:'Data',
							fieldname:"material_model",
							default: item_row.material_model,
							read_only: 1,
							hidden: 0,
							label: __('Material Model')
						},
						{
							fieldtype: "Section Break"
						},
						// 定义弹窗中的表字段(很有参考价值)
						{
							fieldname: "answer_items",
							// 通过fieldtype定义
							fieldtype: "Table",
							label: "Items",
							cannot_add_rows: 0,
							in_place_edit: true,
							reqd: 1,
							data: data,
							// get_data: () => {
							// 	return data;
							// },
							fields: fields
						},
					],
					primary_action: function(values) {
						let yes_items = [];
						values.answer_items.forEach(i => {
							if (i.yes_or_no == 1) {
								yes_items.push({"material_number": values.material_number, "need_date": i.need_date})
							}
						})
						yes_items.forEach(item => {
							console.log(item)
							//循环子表orderitem
							$.each(cur_frm.doc.orderitem, function(i, d) {
								if (d.material_number == item.material_number && d.need_date == item.need_date) {
									console.log(d);
									d.answer_info = d.need_date + "/" + d.assign_qty;
									d.answer_qty = d.assign_qty;
									d.is_default = 1;
								}
							});
						})
						cur_frm.refresh_field("orderitem");
						cur_frm.dirty();
						cur_frm.save();

						dialog.hide();
					},
					primary_action_label: __('Confirm')
				});

				dialog.show();
			})
		}
		else {
			frappe.msgprint("请定位行并且采购方未确认答交")
		}
    },
    page: this.page,
    description: __('Test'),
    ignore_inputs: false,
});


const row_color = frm => {
	frm.fields_dict["orderitem"].$wrapper.find('.grid-body .rows').find(".grid-row").each(function(i, item) { 
		let d = locals["SRM Supply Plan Of Supplier OrderItem"][$(item).attr('data-name')]; 
		let color = d["is_default"] == 0? 'yellow':'transparent'; 
		$(item).find('.grid-static-col').css({'background-color': color}); 
	});
  };
		// 按照采购订单行内码Sum答交数量,不允许超过分配数量
		// 先把采购订单行内码保存为一个set
		// let po_entryid_set = new Set(frm.doc.orderitem.map(function(item) {return item.po_entryid}));
		// // 遍历set中的每一个订单内码,以其作为条件再遍历子表记录分别求和assign_qty、answer_qty
		// po_entryid_set.forEach((po_entryid) => {
		// 	var assign_qty  = 0;
		// 	var answer_qty = 0;
		// 	frm.doc.orderitem.forEach((item)=>{if(item.po_entryid == po_entryid) {assign_qty += item.assign_qty; answer_qty += item.answer_qty }})
		// 	// 比较assign_qty、answer_qty
		// 	if (answer_qty > assign_qty) { frappe.throw(`该订单行 ${po_entryid} 的答交数量之和大于该订单行匹配的分配数量, 不能保存`) }
		// })